package com.rbn.stockmobiledevices.utils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.hibernate.SessionFactory;

import com.rbn.stockmobiledevices.estadisticas.EstadisticaManager;
import com.rbn.stockmobiledevices.estadisticas.Stock;
import com.rbn.stockmobiledevices.estadisticas.internal.HibernateEstadisticaManager;

public class ExcelDownloader {

	private static Logger logger = Logger.getLogger(ExcelDownloader.class);
	private SessionFactory sessionFactory;
	public static SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

	public ExcelDownloader(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	/**
	 * Processes the download for Excel format. It does the following steps:
	 * 
	 * <pre>
	 * 1. Create new workbook
	 * 2. Create new worksheet
	 * 3. Define starting indices for rows and columns
	 * 4. Build layout 
	 * 5. Fill report
	 * 6. Set the HttpServletResponse properties
	 * 7. Write to the output stream
	 * </pre>
	 */
	public void downloadXLS(HttpServletResponse response)
			throws ClassNotFoundException {
		
		logger.debug("Downloading Excel report");

		
		String fecha = sdf.format(new Date());
		
		// 1. Create new workbook
		HSSFWorkbook workbook = new HSSFWorkbook();

		// 2. Create new worksheet
		HSSFSheet worksheet = workbook.createSheet("Stock");

		// 3. Define starting indices for rows and columns
		int startRowIndex = 0;
		int startColIndex = 0;

		// 4. Build layout
		// Build title, date, and column headers
		Layouter.buildReport(worksheet, startRowIndex, startColIndex);

		// 5. Fill report
		FillManager.fillReport(worksheet, startRowIndex, startColIndex, getDatasource());

		// 6. Set the response properties
		String fileName = "stock-"+fecha+".xls";
		response.setHeader("Content-Disposition", "inline; filename=" + fileName);
		
		// Make sure to set the correct content type
		response.setContentType("application/vnd.ms-excel");

		// 7. Write to the output stream
		Writer.write(response, worksheet);
	}

	/**
	 * Retrieves the datasource as as simple Java List. The datasource is
	 * retrieved from a Hibernate HQL query.
	 */
	private List<Stock> getDatasource() {
		EstadisticaManager estadisticaMgr = new HibernateEstadisticaManager(sessionFactory);
		List<Stock> result = estadisticaMgr.getAllStock();
		return result;
	}

}
